package com.freely.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.freely.R;
import com.freely.R2;
import com.freely.component.activity.NavigationActivity;
import com.freely.data.managerUtils.FreelySharedPreferences;
import com.freely.data.network.requestEntities.RQCreateGroupChat;
import com.freely.ui.util.DataVerification;
import com.freely.ui.util.ErrorUtil;
import com.freely.ui.util.VerificationUtil;
import com.freely.ui.viewModel.CreateGroupViewModel;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.io.ByteArrayOutputStream;
import java.io.File;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.lifecycle.ViewModelProviders;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okio.ByteString;


public class CreateGroupActivity extends NavigationActivity {
    private static final String TAG = "CreateGroupActivity";

    public static final int PHOTO_SELECT = 0;

    @BindView(R2.id.group_head_icon)
    ImageView headIcon;//群头像
    @BindView(R2.id.group_name_layout)
    TextInputLayout groupNameLayout;//群名称布局
    @BindView(R2.id.group_name)
    TextInputEditText groupName;//群名
    @BindView(R2.id.group_intro_layout)
    TextInputLayout groupIntroLayout;//群描述布局
    @BindView(R2.id.group_intro)
    TextInputEditText groupIntro;//群描述
    @BindView(R2.id.create)
    AppCompatButton create;//创建按钮

    private BottomSheetDialog dialog;
    private CreateGroupViewModel viewModel;
    private String headIconPath;
    private Bitmap headIconBitmap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_group);
        init();
    }

    private void init() {
        //view model 初始化
        viewModel = ViewModelProviders.of(this).get(CreateGroupViewModel.class);
        //创建群回调
        viewModel.getCreateGroupChat().observe(this, groupSingle -> groupSingle.subscribe(group -> {
            //成功回调
            Toast.makeText(this, "群聊创建成功", Toast.LENGTH_SHORT).show();
            HomeActivity.startActivity(this, HomeActivity.GROUP_CHANGE, group.getGroupId());
        }, ErrorUtil::errorHint).dispose());

    }

    @OnClick(R2.id.group_head_icon)
    void headIconOnClickListener() {
        if (dialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_photo_select, null);
            TextView capture = view.findViewById(R.id.capture);
            TextView gallery = view.findViewById(R.id.gallery);
            capture.setOnClickListener(this::groupHeadIconSelect);
            gallery.setOnClickListener(this::groupHeadIconSelect);
            dialog = new BottomSheetDialog(this);
            dialog.setContentView(view);
        }
        dialog.show();
    }

    void groupHeadIconSelect(View view) {
        switch (view.getId()) {
            case R.id.capture:
                //相机选取群头像
                PhotoSelectActivity.startActivity(
                        CreateGroupActivity.this,
                        PHOTO_SELECT,
                        PhotoSelectActivity.CAPTURE
                );
                break;
            case R.id.gallery:
                //相册选取群头像
                PhotoSelectActivity.startActivity(
                        CreateGroupActivity.this,
                        PHOTO_SELECT,
                        PhotoSelectActivity.GALLERY
                );
                break;
        }
        dialog.cancel();
    }

    @OnTextChanged(R2.id.group_name)
    void groupNameChangedListener(Editable editable) {
        VerificationUtil.groupNameVerificationHint(
                editable.toString(),
                groupNameLayout,
                getString(R.string.group_name_length_error_hint)
        );
    }

    @OnTextChanged(R2.id.group_intro)
    void groupIntroChangedListener(Editable editable) {
        VerificationUtil.groupIntroVerificationHint(
                editable.toString(),
                groupIntroLayout,
                getString(R.string.group_intro_length_error_hint)
        );
    }

    @OnClick(R2.id.create)
    void groupCreateListener() {
        String groupName = this.groupName.getText().toString();
        String groupIntro = this.groupIntro.getText().toString();
        boolean groupNameResult = DataVerification.groupNameLengthVerification(groupName);
        boolean groupIntroResult = DataVerification.groupIntroLengthVerification(groupIntro);
        boolean startCreate = true;
        //群名较检
        if (!groupNameResult) {
            VerificationUtil.errorAnimation(
                    this,
                    groupNameLayout,
                    getString(R.string.group_name_length_error_hint)
            );
            startCreate = false;
        }
        //群公告较检
        if (!groupIntroResult) {
            VerificationUtil.errorAnimation(
                    this,
                    groupIntroLayout,
                    getString(R.string.group_intro_length_error_hint)
            );
            startCreate = false;
        }
        //数据校检失败
        if (!startCreate) {
            return;
        }
        //检查头像
        if (headIconBitmap == null) {
            Toast.makeText(this, "头像不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        //数据校检成功，创建群聊
        Disposable disposable = Single.just(headIconBitmap)
                .subscribeOn(Schedulers.io())
                .subscribe(headIconBitmap -> {
                    //头像由bitmap转为base64
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    headIconBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    byte[] headIconByte = outputStream.toByteArray();
                    String headIcon = ByteString.of(headIconByte).base64();
                    //创建发送请求参数
                    RQCreateGroupChat groupChat = new RQCreateGroupChat(
                            FreelySharedPreferences.getInstance().getUserId(),
                            headIcon,
                            groupName,
                            groupIntro
                    );
                    //发送创建群聊请求
                    viewModel.createGroupChat(groupChat);
                }, throwable -> {
                    //头像错误
                    ErrorUtil.dataReadErrorHint("头像错误",throwable);
                });
        register(disposable);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case PHOTO_SELECT:
                Log.d(TAG, "onActivityResult: 图片选择结果");
                if (resultCode != RESULT_OK) {
                    return;
                }
                Log.d(TAG, "onActivityResult: 成功选择图片");
                headIconPath = data.getStringExtra(PhotoSelectActivity.RESULT);
                Log.d(TAG, "onActivityResult: 判断图片路径");
                if (TextUtils.isEmpty(headIconPath)) {
                    return;
                }
                Log.d(TAG, "onActivityResult: 图片路径正确");
                Glide.with(this)
                        .asBitmap()
                        .load(new File(headIconPath))
                        .apply(RequestOptions.circleCropTransform())
                        .listener(new RequestListener<Bitmap>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                                headIconBitmap = resource;
                                return false;
                            }
                        })
                        .into(headIcon);
                break;
        }
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, CreateGroupActivity.class);
        context.startActivity(intent);
    }
}
